package co.dreamapps.dodoattack.activities;


import java.io.IOException;

import org.andengine.audio.music.Music;
import org.andengine.audio.music.MusicFactory;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.WakeLockOptions;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.util.FPSLogger;
import org.andengine.input.sensor.acceleration.AccelerationData;
import org.andengine.input.sensor.acceleration.IAccelerationListener;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.SimpleBaseGameActivity;

import protocol.OnNewMessageListener;
import protocol.RoomConnection;
import protocol.User;
import co.dreamapps.dodoattack.configuration.Constants;
import co.dreamapps.dodoattack.model.Background;
import co.dreamapps.dodoattack.model.Dodo;
import co.dreamapps.dodoattack.model.MoveDetector;
import co.dreamapps.dodoattack.model.RoomManagerDodoGame;
import co.dreamapps.dodoattack.network.MessageDistpacher;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;


public class GameActivity extends SimpleBaseGameActivity implements IOnSceneTouchListener, OnNewMessageListener, IAccelerationListener {

	/**
	 * Constants
	 */
	private static final int CAMERA_WIDTH = 1080;
	private static final int CAMERA_HEIGHT = 720;

	/**
	 * Fields
	 */
	private Background background;
	private Dodo dodo;
	private Music miMusica;

	/**
	 * Connection
	 */
	private RoomConnection room;
	private RoomManagerDodoGame roomManager;

	/**
	 * Configuracion
	 */
	private boolean isRacing;

	/**
	 * Helpers
	 */
	private MoveDetector moveDetector;

	@Override
	protected void onCreate(Bundle pSavedInstanceState) {
		// Game mode
		Bundle bundle = getIntent().getExtras();
		String message = bundle.getString(Constants.MODE);
		if(message == null)
			finish();
		else if(message.equals(Constants.MODE_RACING)) {
			isRacing = true;
		} else if(message.equals(Constants.MODE_ATTACKING)) {
			isRacing = false;
		} else
			finish();
		//		Toast.makeText(getApplicationContext(), isRacing ? configuration.Constants.MODE_RACING : configuration.Constants.MODE_ATTACKING, Toast.LENGTH_SHORT).show();

		// Creating the movement recognizer
		this.moveDetector = new MoveDetector();
		
		// Registering the message listener
		MessageDistpacher.INSTANCE.setListener(this);

		super.onCreate(pSavedInstanceState);
	}

	@Override
	public EngineOptions onCreateEngineOptions() {
		Camera mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		EngineOptions engineOptions = new EngineOptions(true,ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(), mCamera);
		engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
		engineOptions.getAudioOptions().setNeedsSound(true);
		engineOptions.getAudioOptions().setNeedsMusic(true);
		return engineOptions;
	}

	@Override
	protected void onCreateResources() throws IOException {

		// Background
		background = new Background();		
		background.onCreateResourcesBackground(getTextureManager(), this);

		// Dodo
		dodo = new Dodo(roomManager, CAMERA_WIDTH, isRacing);
		roomManager.dodo = dodo;
		dodo.onCreateResources(getTextureManager(), getEngine(), this);

		try {
			miMusica = MusicFactory.createMusicFromAsset(mEngine.getMusicManager(), this,"sonido/chickenTechno.mp3");
			miMusica.setLooping(true);
			miMusica.setVolume(0.5f);
		} catch (IOException e) {
			Log.e("Alejo", "IOException: Carga de musica");
		}
	}

	@Override
	protected Scene onCreateScene() {

		this.mEngine.registerUpdateHandler(new FPSLogger());
		final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager();
		final Scene scene = new Scene();

		// Background
		background.onCreateSceneBackground(vertexBufferObjectManager);		
		scene.setBackground(background.getBackground());

		// Dodo
		dodo.onCreateScene(getVertexBufferObjectManager(), scene, CAMERA_WIDTH/2, 140);

		// Listener to scene
		scene.setOnSceneTouchListener(this);

		// Starting music
		miMusica.play();

		return scene;
	}

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent touchEvent) {
		if(isRacing) {
			final int xy = moveDetector.touch(touchEvent);
			if(xy != -1) {
				switch (moveDetector.getMoveType()) {
				case MoveDetector.MOVE_LEFT:
					break;
				case MoveDetector.MOVE_RIGHT:
					break;
				case MoveDetector.MOVE_UP:
					dodo.jump();
					break;
				case MoveDetector.MOVE_DOWN:
					break;
				}
			}
		} else {
			final int xy = moveDetector.touch(touchEvent);
			if(xy != -1) {
				switch (moveDetector.getMoveType()) {
				case MoveDetector.MOVE_LEFT:
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(getApplicationContext(), "LEFT "+xy, Toast.LENGTH_SHORT).show();
						}
					});
					break;
				case MoveDetector.MOVE_RIGHT:
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(getApplicationContext(), "RIGHT "+xy, Toast.LENGTH_SHORT).show();
						}
					});
					break;
				case MoveDetector.MOVE_UP:
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(getApplicationContext(), "UP "+xy, Toast.LENGTH_SHORT).show();
						}
					});
					break;
				case MoveDetector.MOVE_DOWN:
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(getApplicationContext(), "DOWN "+xy, Toast.LENGTH_SHORT).show();
						}
					});
					break;
				}
			}
		}
		return false;
	}

	@Override
	public void onAccelerationAccuracyChanged(AccelerationData pAccelerationData) {}

	@Override
	public void onAccelerationChanged(AccelerationData pAccelerationData) {
		if(isRacing)
			dodo.setHorizontalMove(pAccelerationData.getX());
	}

	// ********************************** PROTOCOL EVENTS **********************************

	@Override
	public int onNewMessage(final String message, final User user) {

		runOnUpdateThread(new Runnable() {

			@Override
			public void run() {
				roomManager.onNewMessage(message);
			}
		});

		//		runOnUiThread(new Runnable() {
		//			@Override
		//			public void run() {
		//				Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
		//			}
		//		});
		return message.length();
	}

	@Override
	public void getRoomConnection(RoomConnection connection) {
		this.room = connection;
		this.roomManager = new RoomManagerDodoGame(room, isRacing);
	}

	@Override
	public void onCloseConnection() {}

	// ********************************** PROTOCOL EVENTS **********************************

	// ************************************* LIFE CYCLE *************************************

	@Override
	public void onResumeGame() {
		super.onResumeGame();
		this.enableAccelerationSensor(this);
	}

	@Override
	public void onPauseGame() {
		super.onPauseGame();
		this.disableAccelerationSensor();
	}

	// ************************************* LIFE CYCLE *************************************
}
